package ru.compft.web.adapter;

import org.springframework.util.CollectionUtils;
import ru.compft.common.data.AppPermission;
import ru.compft.common.data.AppRole;
import ru.compft.web.beans.PermissionBean;
import ru.compft.web.beans.RoleBean;

import java.util.List;
import java.util.Set;

/**
 * User: ASUS
 * Date: 09.08.12
 * Time: 21:09
 * Адаптер для преобразование бина в объект БД
 */
public class PermissionAdapter {
    /**
     * Копирование объекта БД в web-бин
     *
     * @param appPermission
     * @param permissionBean
     */
    public static void copyToBean(AppPermission appPermission, PermissionBean permissionBean) {
        if (permissionBean != null && appPermission != null) {

            permissionBean.setId(appPermission.getId());
            permissionBean.setCode(appPermission.getCode());
            permissionBean.setName(appPermission.getName());
            permissionBean.setDescription(appPermission.getDescription());

            // конвертируем роли
            final Set<AppRole> appRoleList = appPermission.getRoles();
            if (!CollectionUtils.isEmpty(appRoleList)) {
                for (AppRole appRole : appRoleList) {
                    final RoleBean roleBean = new RoleBean();
                    RoleAdapter.copyToBean(appRole, roleBean);

                    permissionBean.addRole(roleBean);
                }
            }
        }
    }

    /**
     * Преобразование web-бина в объект БД
     *
     * @param permissionBean
     * @return
     */
    public static AppPermission convertToDataObject(PermissionBean permissionBean) {
        if (permissionBean != null) {
            final AppPermission appPermission = new AppPermission();

            appPermission.setId(permissionBean.getId());
            appPermission.setCode(permissionBean.getCode());
            appPermission.setName(permissionBean.getName());
            appPermission.setDescription(permissionBean.getDescription());

            // конвертируем роли
            final List<RoleBean> roleBeanList = permissionBean.getRoles();
            if (!CollectionUtils.isEmpty(roleBeanList)) {
                for (RoleBean roleBean : roleBeanList) {
                    final AppRole appRole = RoleAdapter.convertToDataObject(roleBean);
                    if (appRole != null) appPermission.addRole(appRole);
                }
            }

            return appPermission;
        }
        return null;
    }
}
